// pages/snake/snake.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        biginpagehidden:false,
        score:0,
        maxscore:0,
        startx:0,
        starty:0,
        endx:0,
        endy:0,
        ground:[],//二维数组
        groundstatus:{},//枚举类，枚举值为css样式变值
        rows:28,
        cols:22,
        snake:[],//数组的坐标列表，末尾为蛇头
        food:[],//当前食物坐标
        direction:"right",//实时方向
        timer:"",//setInterval函数返回值，用以停止
        speed:300,//300ms走一格
        sensitivity:10,//拖了10坐标就算确定输入
        stepturned:false,//防止一步掉头两次
        syspause:true,//时停，为了重置和暂停
        systemms:"开始",//开始 暂停 暂停中... 重新开始
        tipMs:"请按开始键开始\n拖动屏幕控制方向"
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.initMaxscore()
        this.initGround(this.data.rows,this.data.cols)
        this.initSnake()
        this.createFood()
        this.move()//setInterval
    },
    replay:function(){
        this.data.direction="right"
        for(var i=0;i<this.data.rows;i++){
            for(var j=0;j<this.data.cols;j++){
                this.data.ground[i][j]=this.data.groundstatus.empty
            }
        }
        this.data.ground[1][2]=this.data.groundstatus.snakehead[1]
        this.data.ground[1][1]=this.data.groundstatus.snaketail[1]
        //push顺序不能错，最后一个是头
        this.data.snake=[[1,1],[1,2]]
        this.createFood()
        this.setData({
            score:0,
            tipMs:"请按开始键开始\n拖动屏幕控制方向"
        })
    },
    initMaxscore:function(){
        var that=this
        wx.getStorage({
            key:"maxscore",
            success(res){
                that.setData({
                    maxscore:res.data
                })
            }
        });
    },
    initGround:function(rows,cols){
        this.data.groundstatus={
            empty:0,
            snakehead:[11,12,13,14],//上右下左
            snaketail:[21,22,23,24],//上右下左
            food:[3,4,5,6,7,8,9],
            snakefoodbody:[32,42,52,62,72,82,92],
        }
        //二维数组初始化
        for(var i=0;i<rows;i++){
            var arr=[];
            this.data.ground.push(arr);
            for(var j=0;j<cols;j++){
                this.data.ground[i].push(this.data.groundstatus.empty)
            }
        }
    },

    initSnake:function(){
        this.data.ground[1][2]=this.data.groundstatus.snakehead[1]
        this.data.ground[1][1]=this.data.groundstatus.snaketail[1]
        //push顺序不能错，最后一个是头
        this.data.snake.push([1,1])
        this.data.snake.push([1,2])
    },

    //交互操作，移动方式为触摸然后拖动，不用放手也可
    tapStart:function(e){
        this.data.startx=e.touches[0].pageX
        this.data.starty=e.touches[0].pageY
    },
    tapMove:function(e){
        this.tapdetect(this.data.startx,this.data.starty,e.touches[0].pageX,e.touches[0].pageY)
    },
    tapCancel:function(){},
    tapEnd:function(){},

    tapdetect:function(beginx,beginy,endx,endy){
        var horizontal=endx-beginx
        var vertical=endy-beginy
        if((Math.abs(horizontal)>this.data.sensitivity||Math.abs(vertical)>this.data.sensitivity)
        &&this.data.stepturned==false){
            var direction = this.figDir(horizontal,vertical)
            var nowDir = this.data.direction
            if(direction=="left"||direction=="right"){
                if(nowDir=="left"||nowDir=="right"){
                    return;
                }
            }else if(direction=="top"||direction=="bottom"){
                if(nowDir=="top"||nowDir=="bottom"){
                    return;
                }
            }
            this.data.stepturned=true
            this.setData({
                direction:direction,
                startx:endx,
                starty:endy,
            })
        }
    },

    figDir:function(heng,zong){
        var dirStr;
        if(Math.abs(heng)>Math.abs(zong)){
            if(heng>0) dirStr="right"
            else dirStr="left"
        }else{
            if(zong>0) dirStr="bottom"
            else dirStr="top"
        }
        return dirStr
    },

    move:function(){
        var that=this
        this.data.timer=setInterval(function(){
            if(!that.data.syspause)
            that.moveDir(that.data.direction)
        },this.data.speed)
    },

    moveDir:function(dir){
        this.data.stepturned=false
        var snake=this.data.snake
        var len=this.data.snake.length
        var food=this.data.food
        var ground=this.data.ground
        //头将要在的坐标
        var sHeadwillbe = [snake[len-1][0],snake[len-1][1]]
        var headtype = 1
        if(dir=="left"){
            sHeadwillbe[1]-=1
            headtype=3
        }else if(dir=="right"){
            sHeadwillbe[1]+=1
            headtype=1
        }else if(dir=="top"){
            sHeadwillbe[0]-=1
            headtype=0
        }else if(dir=="bottom"){
            sHeadwillbe[0]+=1
            headtype=2
        }
        var frontstatus = this.judgefront(sHeadwillbe)
        //移动逻辑
        if(frontstatus=="open"){
            //snake的头是snake[len-1],尾是snake[0]
            //头到位
            ground[sHeadwillbe[0]][sHeadwillbe[1]] = this.data.groundstatus.snakehead[headtype]
            //背景样式依次前挪，snake数组列表位置依次改变为前一个的
            for(var i=0;i<len-2;i++){
                ground[snake[len-1-i][0]][snake[len-1-i][1]] = ground[snake[len-2-i][0]][snake[len-2-i][1]]
            }
            var tailtype = 3
            ground[snake[0][0]][snake[0][1]] = this.data.groundstatus.empty
            for(var i=0;i<len-1;i++){
                snake[i]=snake[i+1]
            }
            snake[len-1]=sHeadwillbe
            if(snake[1][0]<snake[0][0])tailtype=0
            else if(snake[1][1]>snake[0][1])tailtype=1
            else if(snake[1][0]>snake[0][0])tailtype=2
            else if(snake[1][1]<snake[0][1])tailtype=3
            ground[snake[0][0]][snake[0][1]] = this.data.groundstatus.snaketail[tailtype]
            //末尾成背景
        }else if(frontstatus=="eatfood"){
            //头与食物位置交换而已，其他不变
            var temp = ground[sHeadwillbe[0]][sHeadwillbe[1]]
            ground[sHeadwillbe[0]][sHeadwillbe[1]] = this.data.groundstatus.snakehead[headtype]
            //数字3-9转化为0-6的index，得出的数字是32-92
            ground[snake[len-1][0]][snake[len-1][1]] = this.data.groundstatus.snakefoodbody[temp-3]
            snake.push(sHeadwillbe)
            this.setData({
                score:this.data.score+10
            })
            this.StoreScore()
            //重新创建食物（自带删除)
            this.createFood()

        }else if(frontstatus=="outofrange"||frontstatus=="eatitself"){
            var ms = ""
            if(frontstatus=="outofrange"){
                ms="超出边界"
            }else{
                ms="吃到自己"
            }
            this.snakeOver(ms)
        }
        //移动逻辑结束
        this.setData({
            ground:ground,
            snake:snake,
        })
    },
    //判断头将要碰到什么
    judgefront:function(sHeadwillbe){
        var frontstatus = "outofrange"
        if(sHeadwillbe[0]<0||sHeadwillbe[0]>=this.data.rows
            ||sHeadwillbe[1]<0||sHeadwillbe[1]>=this.data.cols){
            frontstatus = "outofrange"
        }
        else if(this.data.ground[sHeadwillbe[0]][sHeadwillbe[1]]==this.data.groundstatus.empty){
            frontstatus = "open"
        }
        else if(this.data.groundstatus.snakefoodbody.indexOf(this.data.ground[sHeadwillbe[0]][sHeadwillbe[1]])!=-1||this.data.ground[sHeadwillbe[0]][sHeadwillbe[1]]==this.data.groundstatus.snakebody){
            frontstatus = "eatitself"
        }
        else if(this.data.groundstatus.food.indexOf(this.data.ground[sHeadwillbe[0]][sHeadwillbe[1]])!=-1){
            frontstatus = "eatfood"
        }
        return frontstatus
    },
    //创建食物
    createFood:function(){
        var ground=this.data.ground
        var randomArr = []
        for(var i=0;i<this.data.rows;i++){
            for(var j=0;j<this.data.cols;j++){
                if(ground[i][j]==this.data.groundstatus.empty){
                    randomArr.push([i,j])
                }
            }
        }
        var randomxy = randomArr[Math.floor(Math.random()*randomArr.length)]
        ground[randomxy[0]][randomxy[1]]=this.data.groundstatus.food[Math.floor(Math.random()*7)]//0-6就是数字3-9
        this.setData({
            ground:ground,
            food:[randomxy[0],randomxy[1]]
        })
    },
    //已绑定暂停按钮
    snakefunc:function(){
        var systemms = this.data.systemms
        var ms=""
        var pause=false
        if(systemms=="暂停中..."){
            ms="暂停"
            pause=false
        }else if(systemms=="暂停"){
            ms="暂停中..."
            pause=true
        }else if(systemms=="开始"){
            ms="暂停"
            pause=false
            this.setData({
                biginpagehidden:true
            })
        }
        else if(systemms=="重新开始"){//重新开始是回到按开始状态
            ms="开始"
            pause=true
            this.replay()
            this.setData({
                biginpagehidden:false
            })
        }
        this.setData({
            systemms:ms,
            syspause:pause,
        })
    },
    snakeOver:function(ms){
        this.setData({
            syspause:true,
            tipMs:'游戏结束: '+ms,
            biginpagehidden:false,
            systemms:'重新开始',
        })

        /*
        var that=this
        wx.showModal({
            title:'游戏结束',
            content:ms+'\n'+'得分: '+this.data.score,
            confirmText:'重玩',
            showCancel:false,
            success(res){
                if(res.confirm){
                    that.replay()
                }
            }
          })
          */
    },
    //计分器
    StoreScore:function(){
        if(this.data.maxscore<this.data.score){
            var maxscore = this.data.score
            this.setData({
                maxscore:maxscore
            })
            wx.setStorage({
                key:"maxscore",
                data:maxscore,
            })
        }
    },
    /*
    StopSystem:function(){
        clearInterval(this.data.timer)
    }
    */
})